package svl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import xml.cotizacion.Cotizacion;
import xml.factura.Factura;
import xml.solicitudCotizacion.SolicitudCotizacion;
import client.controlador.Controlador;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * Servlet implementation class ParametrosCliente
 */
public class ObtenerFactura extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ObtenerFactura() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		SolicitudCotizacion cotizacion = (SolicitudCotizacion) request.getAttribute("cotizacion");

		XStream xstream = new XStream(new DomDriver());

		xstream.processAnnotations(SolicitudCotizacion.class);

		Object cotizacionDoc = null;

		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;

		Factura fac = null;
		try {
			docBuilder = docBuilderFactory.newDocumentBuilder();

			String xml = xstream.toXML(cotizacion);
			BufferedWriter out = null;
			try {
				out = new BufferedWriter(new FileWriter("c:/xml/Cotizacion2.xml"));
				out.write(xml);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			out.close();
			cotizacionDoc = null;

			File document = Controlador.getInstancia().recibirPedido(cotizacionDoc);

			xstream.processAnnotations(Factura.class);
			fac = (Factura) xstream.fromXML(document);

			System.out.println(fac);

		} catch (Exception e) {

			e.printStackTrace();

		}

		request.setAttribute("factura", fac);

		request.getRequestDispatcher("/WEB-INF/jsp/ReadFacXML.jsp").forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}